package com.tanhua.server.service.impl;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.ReceiveSoundVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.SoundService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class SoundServiceImpl implements SoundService {

    @DubboReference
    private SoundApi soundApi;

    @Autowired
    private FastFileStorageClient client;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 桃花传音，发布语音
     *
     * @param soundFile：语音文件
     */
    @Override
    public void save(MultipartFile soundFile) throws IOException {
        //判断文件是否为空
        if (soundFile.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
        //获取文件全名
        String filename = soundFile.getOriginalFilename();
        //获取文件后缀名
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        //上传文件到fastDFS
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffix, null);
        //将文件上传到fastDFS后返回全路径名
        String path = storePath.getFullPath();
        Sound sound = new Sound();
        sound.setUserId(UserHolder.getUserId());
        sound.setSoundUrl(path);
        sound.setCreated(System.currentTimeMillis());
        String soundId = soundApi.save(sound);
        if (soundId==null){
            throw new BusinessException(ErrorResult.error());
        }
    }

    /**
     * 桃花传音-接收语音
     * @return
     */
    @Override
    public ReceiveSoundVo getSound() {
        //获取语音之前先查询该用户今日已获取语音的次数
        Integer count = soundApi.count(UserHolder.getUserId(),new SimpleDateFormat("yyyyMMdd").format(new Date()));
        if (count>10){
            throw new BusinessException(ErrorResult.builder().errMessage("当日获取语音次数已达上限！").build());
        }
        Sound sound = soundApi.findOne();
        if (sound==null){
            throw new BusinessException(ErrorResult.builder().errMessage("不好意思哦，没有发现更多语音~").build());
        }
        UserInfo info = userInfoApi.findById(sound.getUserId());
        if (info!=null){
            ReceiveSoundVo vo = ReceiveSoundVo.init(info, sound);
            vo.setRemainingTimes(10-count);
            return  vo;
        }else {
            return null;
        }
    }
}
